package org.frasermccrossan.toneitdown;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TimePicker;

public class PickProfile extends Activity {
	
	private ProfileDatabaseHelper pdh;
	private RadioGroup profile_list;
	private ActionMode myActionMode = null;
	Cursor allProfileCursor;
	static final String profileNameTag = "profileName";
	private long longClickedProfile;
	private static final int TIME_DIALOG = 0;
	private static final int HISTORY_DIALOG = 1;
	Button newButton;

	private OnClickListener profilesListener = new OnClickListener () {
        public void onClick(View v) {
        	long profileId = (Long)v.getTag();
        	if (pdh.setProfile(profileId)) {
        		Notify.applyProfile(PickProfile.this);
        		PickProfile.this.finish();
        	}
        }        	
    };

    private OnClickListener buttonListener = new OnClickListener() {
		public void onClick(View v) {
			if (v == newButton) {
				long newProfileId = pdh.createEmptyProfile();
				if (newProfileId != -1) {
					startEdit(newProfileId);
				}
			}
		}
	};

    private OnLongClickListener longListener = new OnLongClickListener() {
    	public boolean onLongClick(View v) {
			if (myActionMode != null) {
	            return false;
	        }
	        longClickedProfile = (Long)((RadioButton) v).getTag();
	        // Start the CAB using the ActionMode.Callback defined above
	        myActionMode = PickProfile.this.startActionMode(myActionModeCallback);
    		return true;
    	}
    };

    private void startEdit(long profileId) {
    	Intent editIntent = new Intent(PickProfile.this, EditProfile.class);
    	editIntent.putExtra(profileNameTag, profileId);
    	startActivity(editIntent);    	
    }
    
    private ActionMode.Callback myActionModeCallback = new ActionMode.Callback() {

	    // Called when the action mode is created; startActionMode() was called
	    @Override
	    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
	        // Inflate a menu resource providing context menu items
	        MenuInflater inflater = mode.getMenuInflater();
	        inflater.inflate(R.menu.profile_context_menu, menu);
	        return true;
	    }

	    // Called each time the action mode is shown. Always called after onCreateActionMode, but
	    // may be called multiple times if the mode is invalidated.
	    @Override
	    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
	        return false; // Return false if nothing is done
	    }

	    // Called when the user selects a contextual menu item
	    @SuppressWarnings("deprecation")
		@Override
	    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
	        switch (item.getItemId()) {
            case R.id.edit_profile:
            	startEdit(longClickedProfile);
                mode.finish(); // Action picked, so close the CAB
                return true;
            case R.id.timed_profile:
            	// all we do here is set up a time picker dialog, the listener does the real work
            	showDialog(HISTORY_DIALOG);
            	mode.finish();
                return true;
            default:
            	return false;
	        }
	    }

	    // Called when the user exits the action mode
	    @Override
	    public void onDestroyActionMode(ActionMode mode) {
	        myActionMode = null;
	    }
	};

	private void setExpiryTime(int hourOfDay, int minute) {
		Calendar now = Calendar.getInstance();
		now.set(Calendar.SECOND, 0);
		now.set(Calendar.MILLISECOND, 0); // why not?
		Calendar expireTime = (Calendar)now.clone();
		expireTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
		expireTime.set(Calendar.MINUTE, minute);
		if (expireTime.before(now)) {
			// make sure expiry time is in the future
			expireTime.add(Calendar.HOUR_OF_DAY, 24);
		}
		pdh.setTimedProfile(longClickedProfile, expireTime.getTimeInMillis());
		pdh.recordSelectedTime(hourOfDay, minute);
		Notify.applyProfile(PickProfile.this);		
		PickProfile.this.finish();
	}
	
	private TimePickerDialog.OnTimeSetListener timeSetListener =
			new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			setExpiryTime(hourOfDay, minute);
		}
	};	
    
	TimePickerDialog makeTimePicker() {
    	Calendar cal = Calendar.getInstance();
    	TimePickerDialog tp = new TimePickerDialog(this, timeSetListener,
    			cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE),
        		DateFormat.is24HourFormat(PickProfile.this));
    	Profile profile = pdh.getProfileById(longClickedProfile);
    	String title = String.format(getString(R.string.profile_expiry_time), profile.name);
    	tp.setTitle(title);
        return tp;		
	}
	
	AlertDialog makeHistoryDialog(ArrayList<HourMinute> history) {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	Profile profile = pdh.getProfileById(longClickedProfile);
    	String title = String.format(getString(R.string.profile_expiry_time), profile.name);
    	builder.setTitle(title)
    	       .setCancelable(true)
    	       .setPositiveButton(getString(R.string.other_time), new DialogInterface.OnClickListener() {
    	           @SuppressWarnings("deprecation")
				public void onClick(DialogInterface dialog, int id) {
    	                showDialog(TIME_DIALOG);
    	           }
    	       })
    	       .setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       });
    	String[] hText = new String[history.size()];
    	int i;
    	for (i = 0; i < history.size(); ++i) {
    		hText[i] = history.get(i).timeAsText(PickProfile.this);
    	}
    	builder.setItems(hText, new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	   AlertDialog aDialog = (AlertDialog)(dialog);
	        	   @SuppressWarnings("unchecked")
				ArrayList<HourMinute> hourMinArray = (ArrayList<HourMinute>)aDialog.getListView().getTag();
	        	   HourMinute hm = hourMinArray.get(id);
	        	   setExpiryTime(hm.hourOfDay, hm.minute);
           }
    	});
    	AlertDialog dialog = builder.create();
    	// store the historylist in the listview so it can be used later
    	View listView = dialog.getListView();
    	listView.setTag(history);
    	return dialog;		
	}
	
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG:
        	return makeTimePicker();
        case HISTORY_DIALOG:
        	ArrayList<HourMinute> history = pdh.getHistory();
        	if (history.size() == 0) {
    			return makeTimePicker();
        	}
        	else {
        		return makeHistoryDialog(history);
        	}
        }
        return null;
    }    
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pdh = new ProfileDatabaseHelper(this);
        setContentView(R.layout.pick_profile);
        Notify.applyProfile(this); // make sure notification is present
        profile_list = (RadioGroup)findViewById(R.id.profile_list);
        newButton = (Button)findViewById(R.id.new_button);
        newButton.setOnClickListener(buttonListener);
    }
    
    @Override
    public void onStart() {
    	super.onStart();
        allProfileCursor = pdh.allProfiles();
        int checkedId = -1;
        long currentProfile = pdh.getCurrentProfileId();
        LayoutInflater inflater = (LayoutInflater)this.getSystemService
        	      (Context.LAYOUT_INFLATER_SERVICE);
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        for (allProfileCursor.moveToFirst(); !allProfileCursor.isAfterLast(); allProfileCursor.moveToNext()) {
        	//RadioButton rb = new RadioButton(this);
        	RadioButton rb = (RadioButton)inflater.inflate(R.layout.profile_radio_layout, null);
        	rb.setText(allProfileCursor.getString(1));
        	rb.setOnClickListener(profilesListener);
        	rb.setOnLongClickListener(longListener);
        	rb.setTag(new Long(allProfileCursor.getLong(0)));
        	profile_list.addView(rb, lp);
        	if (allProfileCursor.getLong(0) == currentProfile) {
        		checkedId = rb.getId();
        	}
        }
        profile_list.check(checkedId);
    	allProfileCursor.close();
    }
    
    @Override
    protected void onStop() {
    	profile_list.removeAllViews();
    	super.onStop();
    }
    
	@Override
	public void onDestroy() {
		pdh.close();
		super.onDestroy();
	}
	
}